
import base64
import  hmac
import  time
import math
from  hashlib  import sha256
import urllib.parse

def createToken(accessKey:str, userId:str)->str:
    res = 'userid' + '/' + userId
    version = '2022-05-01'
    method = 'sha256'
    et = math.ceil(time.time() + 365 * 24 * 3600 )          
    
    forsign = str(et) + "\n" + method + "\n" + res + "\n" + version
    signature = sha1hmac(accessKey, forsign)    

    token = 'version={}&res={}&et={}&method={}&sign={}'.format(version, urllib.parse.quote(res, safe=''), et, method, urllib.parse.quote(signature, safe=''))    
    return  token

def sha1hmac(encrpytKey:str, encryptText:str):    
    hmacCode = hmac.new(key=base64.b64decode(encrpytKey), msg=encryptText.encode(), digestmod=sha256)
    result = base64.b64encode(hmacCode.digest())
    return result.decode()
        
        